<?php

namespace App\V3\V3_2_6\Controllers;

use App\Services\CommonService;
use App\V3\V3_2_6\Models\MaterielProductContentModel;
use App\V3\V3_2_6\Models\MaterielsTypeModel;
use App\V3\V3_2_6\Models\MaterielTypeModel;
use App\V3\V3_2_6\Models\StorageManageModel;
use App\V3\V3_2_6\Services\StorageManageService;
use App\Helper\Utils\Util;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;
use App\V3\V3_2_6\Services\MaterielTypeService;
use App\V3\V3_2_6\Models\HcMaterielTypeModel;
use OSS\OssClient;
use App\V3\V3_2_6\Models\MaterielClassModel;
use App\V3\V3_2_6\Models\StorageModel;
use App\V3\V3_2_6\Models\StorageShelfModel;
use App\V3\V3_2_6\Models\StorageShelfLocationModel;

class MaterielTypeController extends BaseController
{
    /**
     * 创建物料商品信息
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/4 15:51
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        //临时调整-正式上线需删除
        $data = $request->all();
        $data['is_product_materiel'] = empty($data['is_product_materiel'])?0:$data['is_product_materiel'];

        $validator = Validator::make($data, [
            'materiel_name' => 'required',//物料或套件名称
//            'type_name' => 'required',//物料型号
            // 'materiel_img' => 'required',//物料图
            'materiel_no' => 'required',//物料编号
            'is_product_materiel' => [
                Rule::In([0,1]),
            ],//是否为套件;0:否;1:是;
            'materiel_class_id' => [
                'required',
                'integer',
                Rule::notIn([0]),
            ],//物料类型所属二级分类id
            'length' => 'numeric|min:0',//长
            'width' => 'numeric|min:0',//宽
            'height' => 'numeric|min:0',//高
            'weight' => 'numeric|min:0',//体积
            'cost' => 'numeric|min:0',//成本
            'selling_price' => 'numeric|min:0',//销售价格
            'is_use_serial' => [
                Rule::in([0,1])
            ],
//            'add_type' => [
//                Rule::in([0,1])
//            ]
        ],
            [
                'is_product_materiel.in' => '商品类型异常：仅支持商品或套件',
                'materiel_name.required' => '请填写名称',
//                'type_name.required' => '请填写商品型号',
                'materiel_no.required' => '请填写商品编号',
                'materiel_class_id.required' => '请选择商品类型所属分类id',
                'length.numeric' => '商品长度只能为数字',
                'length.min' => '商品长度最小只能为0',
                'width.numeric' => '商品宽度只能为数字',
                'width.min' => '商品宽度最小只能为0',
                'height.numeric' => '商品高度只能为数字',
                'height.min' => '商品高度最小只能为0',
                'weight.numeric' => '商品体积只能为数字',
                'weight.min' => '商品体积最小只能为0',
                'cost.numeric' => '商品成本只能为数字',
                'cost.min' => '商品成本最小只能为0',
                'selling_price.numeric' => '销售价格只能为数字',
                'selling_price.min' => '销售价格最小只能为0',
                'is_use_serial.in' => '参数`是否使用序列号`不合法',
//                'add_type.in' => '参数`新建方式`不合法'
            ]
        );

        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $time=time();
        $this -> operateLog('新建物料',$data,$time);
        $data['length'] = isset($data['length'])?($data['length'] < 0)?0:$data['length']:0;
        $data['width'] = isset($data['width'])?($data['width'] < 0)?0:$data['width']:0;
        $data['height'] = isset($data['height'])?($data['height'] < 0)?0:$data['height']:0;
        $data['weight'] = isset($data['weight'])?($data['weight'] < 0)?0:$data['weight']:0;
        $data['cost'] = isset($data['cost'])?($data['cost'] < 0)?0:$data['cost']:0;
        $data['selling_price'] = isset($data['selling_price'])?($data['selling_price'] < 0)?0:$data['selling_price']:0;
        $data['lower_selling_price'] = isset($data['lower_selling_price'])?($data['lower_selling_price'] < 0)?0:$data['lower_selling_price']:0;
        $data['bar_code'] = empty($data['bar_code'])?'':$data['bar_code'];
        $data['number_prefix'] = empty($data['number_prefix'])?'':$data['number_prefix'];
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $data['created_at'] = $time;
        $data['add_type'] = empty($data['add_type'])?0:$data['add_type'];
        $data['alert_num'] = empty($data['alert_num'])?0:$data['alert_num'];
        $data['price_type'] = empty($data['price_type'])?0:$data['price_type'];
        $data['remark'] = empty($data['remark'])?'':$data['remark'];
        $data['materiel_img'] = empty($data['materiel_img'])?'':$data['materiel_img'];
        $data['attribute'] = empty($data['attribute'])?'':$data['attribute'];
        $data['type_name'] = empty($data['type_name'])?'':$data['type_name'];
//        $data['type_name'] = empty($data['type_name'])?$data['materiel_name']:$data['type_name'];
        $data['materiel_thumbnail_img'] = empty($data['materiel_img'])?'':$data['materiel_img'].config('app.aliyun_oss_thumbnail_url');
        $data['storage_id'] = empty($data['storage_id'])?0:$data['storage_id'];
        $data['in_storage_num'] = !empty($data['in_storage_num'])?$data['in_storage_num']:0;
        $data['serial_info'] = !empty($data['serial_info'])?$data['serial_info']:[];
        $data['shelf_id'] = empty($data['shelf_id'])?0:$data['shelf_id'];
        $data['location_id'] = empty($data['location_id'])?0:$data['location_id'];
        $data['label_id'] = empty($data['label_id'])?'':$data['label_id'];
        $data['label_name'] = empty($data['label_name'])?'':$data['label_name'];
        if(!isset($data['is_use_serial'])){
            $data['is_use_serial'] = 0;
        }
//        if($data['is_product_materiel']) {
//            $data['is_use_serial'] = 0;
//        }

        //检查物料商品编号是否存在
//        $checkNo = MaterielTypeService::checkNo($data);
//
//        if(!$checkNo) {
//            return $this->fail('', '商品编号已存在，请重新输入');
//        }
        if(!empty($data['bar_code'])){
            $mInfo = MaterielTypeModel::where(['main_id'=>$this->getMainUserId(),'bar_code'=>$data['bar_code'],'delete_flag'=>0])->first();
            if(!empty($mInfo)){
                return $this->fail('', '物料`'.$mInfo['materiel_name'].'的条形码'.$data['bar_code'].'`已存在!');
            }
        }

        if(!empty($data['number_prefix'])){
            $mInfo = MaterielTypeModel::where(['main_id'=>$this->getMainUserId(),'number_prefix'=>$data['number_prefix'],'delete_flag'=>0])->first();
            if(!empty($mInfo)){
                return $this->fail('', '物料`'.$mInfo['materiel_name'].'的编号前缀'.$data['number_prefix'].'`已存在!');
            }
        }
        //验证商品信息是否已存在
        $checkMaterielInfo = MaterielTypeService::checkMaterielInfo($data);
        if(!$checkMaterielInfo) {
            return $this->fail('', '物料类型`'.$data['materiel_name'].'-'.$data['type_name'].'`已存在');
        }

        $time = time();
        $data['in_storage_time'] = !empty($data['in_storage_time'])?$data['in_storage_time']:$time;
        $data['batch_title'] = $this->batchTitle();

        if($data['add_type']) {
            if(empty($data['storage_id'])) {
                return $this->fail('','请选择入库仓库');
            }
        }

        $this->operateLog('新建物料商品', $data, $time);
        if($data['is_product_materiel']) {//创建套件
//            if(empty($data['product_content'])) {
//                return $this->fail('', '请设置套件内容');
//            }

            $result = MaterielTypeService::addProductMateriel($data, $time, $this->isUseShelf());
        }
        else {//创建普通商品
            $result = MaterielTypeService::add($data, $time, $this->isUseShelf());
        }

        CommonService::operateResult($this->getUserId(),$time,$result);
        return response()->json(
            $result
        );
    }

    public function del(Request $request)
    {
        if(empty($request->id)) {
            return $this->fail('', '参数`物料商品id`缺失');
        }

        $arr = array_filter(explode(',', $request->id), function($v) { return $v !== ''; });

        $checkTypeInfo = StorageManageModel::where('delete_flag', 0)
            ->where('in_storage_num', '!=', 0)
            ->whereIn('type_id', $arr)->first();

        if(!empty($checkTypeInfo)) {
            return $this->fail('', '若需要删除该物料类型，需删除该类型下所有的在库数据');
        }

        DB::beginTransaction();

        try {
            MaterielsTypeModel::whereIn('id', $arr)->update(['delete_flag' => 1]);
            StorageManageModel::where('in_storage_num', 0)->whereIn('type_id', $arr)->update(['delete_flag' => 1]);

            MaterielProductContentModel::whereIn('product_id', $arr)->update(['delete_flag' => 1]);

            $this->log('删除物料类型', $arr);
            DB::commit();
            return $this->success();
        }
        catch(Exception $e) {
            DB::rollBack();
            return $this->fail('', $e->getMessage());
        }
    }

    /**
     * 删除指定商品信息
     * 废弃
     * 废弃时间 2022-08-23 17：52
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/4 16:17
     * @return \Illuminate\Http\JsonResponse
     */
    public function del1(Request $request)
    {
        if(empty($request->id)) {
            return $this->fail('', '参数`物料商品id`缺失');
        }

        $checkMateriel = MaterielTypeService::checkMateriel(
            $this->getMainUserId(),
            $request->id
        );

        if(!$checkMateriel) {
            return $this->fail('', '您要删除的物料商品不存在，请重试');
        }

        $checkStorage = StorageManageService::checkMatierlInStorageOrNot(
            $request->id,
            $this->getMainUserId(),
        );

        if(!$checkStorage) {
            return $this->fail('', '若需要删除该物料商品，需删除库存中所有相关数据');
        }

        MaterielsTypeModel::where('id', $request->id)->update(['delete_flag' => 1]);

        $this->log('删除物料类型', $request->id);
        return $this->success();
    }

    /**
     * 编辑商品详细
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/5 9:37
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',//物料名称
            'materiel_name' => 'required',//物料名称
//            'type_name' => 'required',//物料型号
            // 'materiel_img' => 'required',//物料图
            'materiel_no' => 'required',//物料编号
            'materiel_class_id' => [
                'required',
                'integer',
                Rule::notIn([0]),
            ],//物料类型所属二级分类id
            'selling_price' => 'numeric|min:0',//销售价格
        ],
            [
                'id.required' => '参数`物料商品id`缺失',
                'materiel_name.required' => '请填写商品名称',
                'materiel_no.required' => '请填写商品编号',
                'materiel_no.size' => '商品编号必须为8位',
                'materiel_class_id.required' => '请选择商品类型所属分类id',
                'selling_price.numeric' => '销售价格只能为数字',
                'selling_price.min' => '销售价格最小只能为0',
            ]
        );

        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $time = time();
        $this->operateLog('编辑物料商品', $data,$time);
        if(isset($data['bar_code'])) {
//            $mInfo = MaterielTypeModel::where(['main_id' => $this->getMainUserId(), 'bar_code' => $data['bar_code'], 'delete_flag' => 0])->first();
            $mInfo = MaterielTypeModel::where([
                'main_id' => $this->getMainUserId(),
                'bar_code' => $data['bar_code'],
                'delete_flag' => 0
            ])
                ->where('id', '!=', $data['id'])
                ->first();
            if (!empty($mInfo)) {
                return $this->fail('', '物料`' . $mInfo['materiel_name'] . '的条形码' . $data['bar_code'] . '`已存在!');
//                if ($mInfo['id'] != $data['id']) {
//                    return $this->fail('', '物料`' . $mInfo['materiel_name'] . '的条形码' . $data['bar_code'] . '`已存在!');
//                }
            }
        }
        if(isset($data['number_prefix'])){
            $mInfo = MaterielTypeModel::where(['main_id'=>$this->getMainUserId(),'number_prefix'=>$data['number_prefix'],'delete_flag'=>0])
                ->where('id', '!=', $data['id'])->first();
            if(!empty($mInfo)){
                return $this->fail('', '物料`'.$mInfo['materiel_name'].'的编号前缀'.$data['number_prefix'].'`已存在!');
            }
        }
        $data['length'] = isset($data['length'])?($data['length'] < 0)?0:$data['length']:0;
        $data['is_product_materiel'] = !isset($data['is_product_materiel'])?0:$data['is_product_materiel'];
        $data['width'] = isset($data['width'])?($data['width'] < 0)?0:$data['width']:0;
        $data['height'] = isset($data['height'])?($data['height'] < 0)?0:$data['height']:0;
        $data['weight'] = isset($data['weight'])?($data['weight'] < 0)?0:$data['weight']:0;
        $data['cost'] = isset($data['cost'])?($data['cost'] < 0)?0:$data['cost']:0;
        $data['selling_price'] = isset($data['selling_price'])?($data['selling_price'] < 0)?0:$data['selling_price']:0;
        $data['lower_selling_price'] = isset($data['lower_selling_price'])?($data['lower_selling_price'] < 0)?0:$data['lower_selling_price']:0;
        $data['is_use_serial'] = empty($data['is_use_serial'])?0:1;
        $data['bar_code'] = empty($data['bar_code'])?'':$data['bar_code'];
        $data['number_prefix'] = empty($data['number_prefix'])?'':$data['number_prefix'];
        $data['main_id'] = $this->getMainUserId();
        $data['updated_at'] = $time;
        $data['alert_num'] = empty($data['alert_num'])?0:$data['alert_num'];
        $data['remark'] = empty($data['remark'])?'':$data['remark'];
        $data['materiel_img'] = empty($data['materiel_img'])?'':$data['materiel_img'];
        $data['materiel_thumbnail_img'] = empty($data['materiel_img'])?'':$data['materiel_img'].config('app.aliyun_oss_thumbnail_url');
        $data['attribute'] = empty($data['attribute'])?'':$data['attribute'];
        $data['type_name'] = empty($data['type_name'])?'':$data['type_name'];
        $goodsInfo = MaterielTypeService::goodsInfo($data);

        if(!empty($data['materiel_img'])) {
            $materielImg = $data['materiel_img'];
            $materielImgGroup = array_filter(explode(',', $data['materiel_img']), function($v) { return $v !== ''; });

            //$data['materiel_img'] = $materielImgGroup[0];
            $data['materiel_img_group'] = $materielImg;
        }
        else {
            $data['materiel_img_group'] = '';
        }

        if(!empty($goodsInfo)){
            if($goodsInfo['is_use_serial'] != $data['is_use_serial']){
                $storageManageInfo = StorageManageModel::where([
                    'type_id'=> $goodsInfo['id'],
                    'delete_flag'=>0
                ])->where('in_storage_num','>',0)->first();
                if(!empty($storageManageInfo)){
                    if($data['is_use_serial']==1){
                        return $this->fail('', '库存中存在该商品，不能开启序列号，需清空库存');
                    }else{
                        return $this->fail('', '库存中存在该商品，不能关闭序列号，需清空库存');
                    }
                }
            }
            if($goodsInfo['selling_price'] != $data['selling_price']){
                if($goodsInfo['price_num'] == 0){
                    $data['price_one'] = $data['selling_price'];
                    $data['price_num'] = 1;
                }elseif($goodsInfo['price_num'] == 1){
                    $data['price_two'] = $data['selling_price'];
                    $data['price_num'] = 2;
                }elseif($goodsInfo['price_num'] == 2){
                    $data['price_three'] = $data['selling_price'];
                    $data['price_num'] = 3;
                }elseif($goodsInfo['price_num'] == 3){
                    $data['price_four'] = $data['selling_price'];
                    $data['price_num'] = 4;
                }elseif($goodsInfo['price_num'] == 4){
                    $data['price_five'] = $data['selling_price'];
                    $data['price_num'] = 0;
                }
            }

            if($data['is_product_materiel']) {
                $result = MaterielTypeService::editProductMateriel($data,$this->getUserId());
            }
            else {
                $result = MaterielTypeService::editMateriel($data,$this->getUserId());
                MaterielTypeService::updateProductInfo($data);
            }
        }else{
            $result =['code'=>1,'msg'=>'物料商品信息，不存在！','data'=>''];
        }

        return response()->json($result);
    }

    /**
     * 获取物料商品指定信息
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/5 9:39
     * @return \Illuminate\Http\JsonResponse
     */
    public function info(Request $request)
    {
        if(empty($request->id)) {
            return $this->fail('', '参数`物料类型id`缺失');
        }

        return $this->success(
            MaterielTypeService::info(
                $request->id
            )
        );
    }

    /**
     * 物料列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/5 10:39
     * @return \Illuminate\Http\JsonResponse
     */
    public function select(Request $request)
    {
        $keyword = empty($request->keyword)?'':$request->keyword;
        $condition = [];

        if(!empty($request->materiel_class_id)) {
            $condition['a.materiel_class_id'] = ['EQ' => $request->materiel_class_id];
        }

        return $this->success(
            MaterielTypeService::materielTypeSelect(
                $this->getMainUserId(),
                $keyword,
                $condition,
                $request->pageSize,
                $request->currentPage,
                $request->is_product_materiel
            )
        );
    }

    /**
     * 物料商品列表-含库存信息
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/5 11:22
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required',//物料名称
            'currentPage' => 'required',//成本
//            'is_product_class' => [
//                'required',
//                Rule::in([0,1])
//            ],
        ],
            [
                'pageSize.required' => '参数`页面大小`缺失',
                'currentPage.required' => '参数`页码`缺失',
//                'is_product_class' => '参数`类型`缺失'
            ]
        );

        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }


//        $isProductMateriel = isset($data['is_product_materiel'])?$data['is_product_materiel']:0;

        if($this->getUserId() == $this->getMainUserId()) {
            $user['e.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            if($this->isShareStorage()) {
                $user['e.main_id'] = ['EQ' => $this->getMainUserId()];
            }else {
                $user['e.user_id'] = ['EQ' => $this->getUserId()];
            }
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['user_type'] = $this->getUserTpye();
        $data['is_share_storage_operate'] = $this->isShareStorageOperate();
        return $this->success(MaterielTypeService::list($user,$data));

    }

    public function randNo()
    {
        $data['materiel_no'] = Util::randStr(8);
        $data['main_id'] = $this->getMainUserId();

        while(!empty(MaterielsTypeModel::checkMaterielTypeRandCode($data))) {
            $data['materiel_no'] = Util::randStr(8);
        }

        unset($data['main_id']);

        return $this->success($data);
    }

    public function editMaterielCost(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',//物料名称
            'cost' => 'min:0',//成本
        ],
            [
                'id.required' => '参数`物料商品id`缺失',
                /* 'cost.numeric' => '商品成本只能为数字', */
                'cost.min' => '商品成本最小只能为0',
            ]
        );

        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $this->log('修改成本价', $data);
        MaterielTypeService::editMaterielCost($data);
        return $this->success();
    }

    public function packageInfo(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',//物料名称
        ],
            [
                'id.required' => '参数`物料商品id`缺失',
            ]
        );

        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return $this->success(
            MaterielTypeService::packageInfo($data)
        );
    }
}
